package com.cw.japp

import java.util.Date;

class User {

	transient springSecurityService
	String firstName
	String lastName
	String username
	String password
	boolean enabled = true
	boolean accountExpired
	boolean accountLocked
	boolean passwordExpired
	String email
	Date birthDate
	String description
	String pictureUri
	Date lastLogin
	Integer status
	Date lastModifiedDate
	Date createdDate
	Address address

	static transients = ['springSecurityService']
	
	static hasMany = [adminAnnouncements: AdminAnnouncement,
	                  chatsForOwnerId: Chat,
	                  chatsForUserId: Chat,
	                  clients: Client,
	                  modelEarnedTokens: ModelEarnedToken,
	                  modelShowTimes: ModelShowTime,
	                  recordings: Recording,
	                  sessionDatas: SessionData,
	                  userChatSettingses: UserChatSettings,
	                  userContactsForOwnerId: UserContact,
	                  userContactsForUserId: UserContact,
	                  userExpenseDetails: UserExpenseDetail,
	                  userProfiles: UserProfile,
	                  userPurchaseDetails: UserPurchaseDetail,
	                  userSettingses: UserSettings,
	                  userTotalAvailableTokens: UserTotalAvailableToken]
	static belongsTo = [Address]

	// TODO you have multiple hasMany references for class(es) [UserContact, Chat] 
	//      so you'll need to disambiguate them with the 'mappedBy' property:
	static mappedBy = [chatsForOwnerId: "usersByOwnerId",
	                   chatsForUserId: "usersByUserId",
	                   userContactsForOwnerId: "usersByOwnerId",
	                   userContactsForUserId: "usersByUserId"]

	static constraints = {
		username blank: false, unique: true
		password blank: false
		birthDate nullable: true
		description nullable: true
		pictureUri nullable: true
		lastLogin nullable: true
		status nullable: true
		lastModifiedDate nullable: true
		createdDate nullable: true
		address nullable: true
		email email: true, blank: false
	}

	static mapping = {
		password column: '`password`'
	}

	Set<Role> getAuthorities() {
		UserRole.findAllByUser(this).collect { it.role } as Set
	}

	def beforeInsert() {
		encodePassword()
	}

	def beforeUpdate() {
		if (isDirty('password')) {
			encodePassword()
		}
	}

	protected void encodePassword() {
		password = springSecurityService.encodePassword(password)
	}
}
